package cn.italkcloud.cph.config.handler;

import cn.italkcloud.cph.helper.AuthHelper;
import cn.italkcloud.cph.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 全局请求拦截器
 *
 * @author dominate
 * @since 2023-06-14
 */
@Slf4j
public class GlobalRequestHandler implements HandlerInterceptor {

    private static final List<String> EXCLUDE_PATHS = Arrays.asList("/auth/login", "/auth/logout");

    /**
     * 两种校验方式
     * <p>
     * 1.Token
     * 2.Api Token
     *
     * @param request  请求体
     * @param response 返回结果
     * @param handler  处理器
     * @return 是否放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String path = request.getRequestURI();
        log.info("Request path {}", path);
        if (EXCLUDE_PATHS.contains(path)) {
            return true;
        }
        // 请求里有 Token ，进行用户检查
        String token = request.getHeader(AuthHelper.defaultUserTokenKey());
        if (!StringUtil.isEmpty(token)) {
            // TODO 简化版本不校验接口权限
            return AuthHelper.isValid(token);
        }
        // 进行服务端检查
        String apiToken = request.getHeader(AuthHelper.defaultApiTokenKey());
        if (StringUtil.isEmpty(apiToken)) {
            log.warn("Refused request path {} ", path);
            return false;
        }
        if (!AuthHelper.isValidApiToken(apiToken)) {
            log.warn("Refused request path {} api token {}", path, apiToken);
            return false;
        }
        return true;
    }

}
